import React, { FC, useState } from 'react'
import { produce } from 'immer'

const ImmerDemo: FC = () => {
    const [userInfo, setUserInfo] = useState({ name: '滕轶男', age: 20 })
    function changeAge() {
        // 不可变数据 - 不去修改state的值，而是传入新的值
        // setUserInfo({
        //     ...userInfo, // 解构
        //     age: 24,
        // })
        // immer 写法
        setUserInfo(
            produce((draft: any) => {
                draft.age = 21
            })
        )
    }

    const [list, setList] = useState(['x', 'y'])
    function addItem() {
        // setList(list.concat('z'))
        // setList([...list, 'z'])
        // immer 写法
        setList(
            produce((draft: any) => {
                draft.push('h')
            })
        )
    }
    return (
        <>
            <h2>State 不可变数据</h2>
            <div>{JSON.stringify(userInfo)}</div>
            <button onClick={changeAge}> change age </button>
            <div>{JSON.stringify(list)}</div>
            <button onClick={addItem}> add item </button>
        </>
    )
}

export default ImmerDemo
